import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/token'


//定义路由关系
const routes = [
    {
        path: '/login',
        component: () => import('@/views/Login.vue')
    },
    {
        path: '/',
        component: () => import('@/views/Layout.vue'),
        redirect: '/admin/scenic/all',
        children: [
            {
                path: '/upload',
                component: () => import('@/views/business/Upload.vue')
            },
            {
                path: '/travel/feedback',
                component: () => import('@/views/business/Feedback.vue')
            },
            {
                path: '/admin/scenic/all',
                component: () => import('@/views/scenic/ScenicBoth.vue')
            },
            {
                path: '/admin/scenic/list',
                component: () => import('@/views/scenic/ScenicHot.vue')
            },
            {
                path: '/travel/foods/list',
                component: () => import('@/views/food/FoodCategory.vue')
            },
            {
                path: '/travel/actives/list',
                component: () => import('@/views/activity/ActivityCategory.vue')
            },
            {
                path: '/user/info',
                component: () => import('@/views/user/UserInfo.vue')
            },
            {
                path: '/user/avatar',
                component: () => import('@/views/user/UserAvatar.vue')
            },
            {
                path: '/user/resetPassword',
                component: () => import('@/views/user/UserResetPassword.vue')
            },
        ]
    }
];

//创建路由器
const router = createRouter({
    history: createWebHistory(),
    routes: routes
})
// 登录访问拦截 => 默认是直接放行的
// 根据返回值决定，是放行还是拦截
// 返回值：
// 1. undefined / true  直接放行
// 2. false 拦回from的地址页面
// 3. 具体路径 或 路径对象  拦截到对应的地址
//    '/login'   { name: 'login' }
router.beforeEach((to) => {
    // 如果没有token, 且访问的是非登录页，拦截到登录，其他情况正常放行
    const useStore = useUserStore()
    if (!useStore.token && to.path !== '/login') return '/login'
  })
  


//导出路由
export default router
